package security

import java.security.MessageDigest
import java.util.Base64
import encrypts._

import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import com.google.common.hash.Hashing
import com.nimbusds.jose.util.StandardCharset

object Encode {
  def base642Byte(encodedText: String) = Base64.getDecoder.decode(encodedText)

  def byte2Base64(textByte: Array[Byte]) = Base64.getEncoder.encodeToString(textByte)

  def pwdVerify(hash: String, pwd: String) = Argon2Encode.verify(hash, pwd)

  def pwdHashed(pwd: String): String = Argon2Encode.hash(pwd)

  def hashMD5(message: String): String = MessageDigest.getInstance("MD5").digest(message.getBytes).map("%02x".format(_)).mkString

  def hashSHA256(message: String): String = MessageDigest.getInstance("SHA-256").digest(message.getBytes).map("%02x".format(_)).mkString

  def hmacSHA256(message: String, secret: String): String = {
    val mac = Mac.getInstance("HmacSHA256")
    mac.init(new SecretKeySpec(secret.getBytes(), "HmacSHA256"))
    mac.doFinal(message.getBytes).map("%02x".format(_)).mkString
  }

  def hashFNV1a64(message: String) = {
    /**
     * // 32位
     * INV = 2166136261
     * P = 16777619 // 2^24+2^8+0x93
     * *
     * // 64位
     * INV = 14695981039346656037
     * P = 1099511628211 // 2^40+2^8+0xb3
     *
     */
    val INV = BigInt("14695981039346656037")
    val P = BigInt("1099511628211")
    var C = INV
    for (d <- message.getBytes) {
      C = C.^(BigInt(d))
      C = C.*(P).&(0x7fffffffffffffffL)
    }
    C.toLong
  }

  def hashFNV1a32(message: String) = {
    val INV = 21_6613_6261L
    val P = 16777619
    var C = INV
    for (d <- message.getBytes) {
      C = C.^(d)
      C = C.*(P).&(0x7fff_ffff)
    }
    C.toInt
  }

  def baseN(num:Long, b:Int):String = ""

  def murmurHash32(string: String) = {
    Hashing.murmur3_32().newHasher().putString(string,StandardCharset.UTF_8).hash()
  }


}
